package com.demo.text;

import com.demo.entity.Student;
import com.sun.tools.javac.code.Attribute;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@Slf4j
public class classs {
    public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException, ClassNotFoundException {
        Class clazz = Class.forName("com.demo.entity.Student");
        // 创建类对象（方式一）
        Student student = (Student) clazz.newInstance();
        // 获取所有构造方法
        Constructor[] constructors = clazz.getConstructors();
        // 获取无参构造
        Constructor constructor = clazz.getConstructor();
        // 创建类对象（方式二）
        Student student1 = (Student) constructor.newInstance();
        // 获取有参构造
        Constructor constructor1 = clazz.getConstructor(String.class, String.class);
        // 创建类对象（方式二）
        Student student2 = (Student) constructor1.newInstance("001", "zhiqiang");
        // 获取private修饰的无参构造方法
        Constructor declaredConstructor = clazz.getDeclaredConstructor();
        // 设置突破封装
        declaredConstructor.setAccessible(true);
        // 必须突破封装才可以调用方法
        Student student3 = (Student) declaredConstructor.newInstance();

        // 获取方法 参数方法名，参数类对象（调用私有方法通构造方法，使用declared，再setAccessible突破封装）
        Method method = clazz.getMethod("aa",String.class);
        // 获取所有方法
        Method[] methods = clazz.getMethods();
        // 调用方法
        method.invoke(student, "智强");

        // 获取字段（室友private修饰）
        Field name = clazz.getDeclaredField("name");
        name.setAccessible(true);
        name.set(student,"zhiqiang");
        System.out.println(name.get(student));
    }
}
